package cn.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/ServletCookieTest")
public class ServletCookieTest extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = request.getCookies();
        boolean flag = false;
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年mm月dd日 HH:mm:ss");
        String format_date = simpleDateFormat.format(date);
        String encode_format_date = URLEncoder.encode(format_date, "utf-8");
        if (cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if("lastTime".equals(name)){
                    flag=true;
                    cookie.setValue(encode_format_date);
                    response.addCookie(cookie);
                    cookie.setMaxAge(60*60*24*30);
                    String value = cookie.getValue();
                    String decode_format_date = URLDecoder.decode(value, "utf-8");
                    response.getWriter().write("<h1>欢迎回来，您上次访问时间为："+decode_format_date+"</h1>");
                    break;
                }
            }
        }
        if(cookies==null || cookies.length==0 || flag==false){
            Cookie cookie = new Cookie("lastTime",encode_format_date);
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);
            response.getWriter().write("<h1>欢迎登陆</h1>");
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);

    }
}
/*
访问当前页面，如若第一次访问，则现实 欢迎访问，如若是第二次访问，则现实上次访问时间
 */